package com.seari.vehbaseF.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.seari.vehbaseF.bean.BaseInfoBean;
import com.seari.vehbaseF.bean.DeviceParamBean;
import com.seari.vehbaseF.main.StartUpClass;
import com.seari.vehbaseF.mapper.BaseInfoMapper;
import com.seari.vehbaseF.service.BaseInfoService;
import com.seari.vehbaseF.util.ExcelUtils;
import com.seari.vehbaseF.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("BaseInfoService")
public class BaseInfoServiceImpl implements BaseInfoService {

    private static String baseInfoPath = "/sql/baseinfo.xlsx";

    @Autowired
    public BaseInfoMapper baseInfoMapper;


    @Override
    public void addBaseInfoList() throws IOException, ParseException {
        initNetWorkInitialData();
    }

    public void initNetWorkInitialData() throws ParseException, IOException {
        String path = System.getProperty("user.dir")+baseInfoPath;
        String token= StartUpClass.config.getProperty("RealDataHTTP_token");
        String projectPath = StartUpClass.config.getProperty("BaseInfoHTTP_url")+token;
        String dataMappingPath = StartUpClass.config.getProperty("DeviceParamHTTP_url")+token;
        List<BaseInfoBean> baseInfoBeans =new ArrayList<>();
        List<DeviceParamBean> deviceParamBeans =new ArrayList<>();
        String project = HttpClientUtil.getInstance().sendHttpPost(projectPath);
        if (StringUtils.isNotBlank(project)) {
            Map<String,Object> projectMap = (Map<String,Object>) JSONObject.parse(project);
            List<Map<String, Object>> projectList = (List<Map<String, Object>>) projectMap.get("data");
            Date currentData=new Date();
            for (Map<String,Object> pro :
                    projectList) {
                BaseInfoBean baseInfoBean =new BaseInfoBean();
                Integer projectCode = (Integer) pro.get("projectCode");
                String projectName = (String) pro.get("projectName");
                String OnlineTime = (String) pro.get("OnlineTime");
                Date dataOnlineTime = null;
                if (OnlineTime!=null){
                    dataOnlineTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(OnlineTime);
                }
                String params="{ProjectCode:"+projectCode+"}";
                String deviceParam = HttpClientUtil.getInstance().sendHttpPost(dataMappingPath, params);
                if (StringUtils.isNotBlank(deviceParam)) {
                    Map<String,Object> deviceParamMap = (Map<String,Object>)JSONObject.parse(deviceParam);
                    List<Map<String, Object>> deviceParamList = (List<Map<String, Object>>) deviceParamMap.get("data");
                    for (Map<String,Object> param :
                            deviceParamList) {
                        DeviceParamBean deviceParamBean =new DeviceParamBean();
                        Integer DeviceID = (Integer) param.get("DeviceID");
                        Integer DataCode = (Integer) param.get("DataCode");
                        String DataName = (String) param.get("DataName");
                        deviceParamBean.setProjectCode(projectCode);
                        deviceParamBean.setDeviceId(DeviceID);
                        deviceParamBean.setDataCode(DataCode);
                        deviceParamBean.setDataName(DataName);
                        deviceParamBeans.add(deviceParamBean);
                    }
                }
                baseInfoBean.setProjectCode(projectCode);
                baseInfoBean.setProjectName(projectName);
                baseInfoBean.setOnlineTime(dataOnlineTime);
                baseInfoBean.setGmtCreate(currentData);
                baseInfoBean.setGmtModified(currentData);
                baseInfoBeans.add(baseInfoBean);
            }
            Map<Integer,String> temp=new HashMap();
            List<List<Object>> lists = ExcelUtils.readExcelFirstSheet(new File(path));
            for (int i = 0; i < baseInfoBeans.size(); i++) {
                BaseInfoBean baseInfoBean = baseInfoBeans.get(i);
                for (int j = 1; j < lists.size()-1; j++) {
                    List<Object> objects = lists.get(j);
                    if (baseInfoBean.getProjectName().contains((String)objects.get(1))||((String) objects.get(1)).contains(baseInfoBean.getProjectName())){
                        getExcelCell(baseInfoBean, objects);
                        temp.put(j,"");
                        break;
                    }
                }
            }
            for (int i = 1; i < lists.size()-1; i++) {
                if (!temp.containsKey(i)){
                    List<Object> objects = lists.get(i);
                    BaseInfoBean baseInfoBean =new BaseInfoBean();
                    getExcelCell(baseInfoBean, objects);
                    baseInfoBean.setGmtCreate(currentData);
                    baseInfoBean.setGmtModified(currentData);
                    baseInfoBeans.add(baseInfoBean);
                }
            }
        }
        baseInfoMapper.cleanOldBaseInfo();
        subBaseInfoList(baseInfoBeans);
        baseInfoMapper.cleanOldDeviceParam();
        subBaseList(deviceParamBeans);
    }

    private void getExcelCell(BaseInfoBean baseInfoBean, List<Object> objects) {
        baseInfoBean.setBaseName((String) objects.get(1));
        setLineInfo((String) objects.get(2),baseInfoBean);
        baseInfoBean.setBaseAdd((String) objects.get(3));
        String po = (String) objects.get(4);
        baseInfoBean.setAddLng(po.substring(0, po.indexOf(",")));
        baseInfoBean.setAddLat(po.substring(po.indexOf(",") + 1));
        baseInfoBean.setTotalArea(((BigDecimal)objects.get(5)).setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
        baseInfoBean.setArctArea(((BigDecimal)objects.get(6)).setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString());
        baseInfoBean.setSituation((String) objects.get(7));
    }

    /**
     * 0-99 转换
     * @param station
     * @return
     */
    private void setLineInfo(String station,BaseInfoBean baseInfoBean) {
        List<Integer> list=new ArrayList<>();
        String ids = "";
        String[] split = station.split("、");
        for (String string:split) {
            String line = string.replace("号线", "");
            int number=0;
            for (int i = 0; i < line.length(); i++) {
                switch(line.substring(i,i+1)){
                    case "十":
                        if (number==0){
                            number+=10;
                        }else{
                            number=number*10;
                        }
                        break;
                    case "零":
                        number+=0;
                        break;
                    case "一":
                        number+=1;
                        break;
                    case "二":
                        number+=2;
                        break;
                    case "三":
                        number+=3;
                        break;
                    case "四":
                        number+=4;
                        break;
                    case "五":
                        number+=5;
                        break;
                    case "六":
                        number+=6;
                        break;
                    case "七":
                        number+=7;
                        break;
                    case "八":
                        number+=8;
                        break;
                    case "九":
                        number+=9;
                        break;
                    default:
                        number+=0;
                        break;
                }
            }
            list.add(number);
        }
        list.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
        int tag=0;
        for (int i = 0; i < list.size(); i++) {
            ids+=list.get(i)+"-";
            if (i==0){
                tag=list.get(i)*1000;
            }else{
                tag+=list.get(i);
            }
        }
        baseInfoBean.setLineNo(station);
        baseInfoBean.setLineId(ids.substring(0,ids.length()-1));
        baseInfoBean.setLineTag(tag);
    }


    public void subBaseList(List<DeviceParamBean> list){
        if (list.size()>500){
            baseInfoMapper.addDeviceParamList(list.subList(0,500));
            List<DeviceParamBean> deviceParamBeans = list.subList(500, list.size());
            subBaseList(deviceParamBeans);
        }else{
            baseInfoMapper.addDeviceParamList(list);
        }

    }

    public void subBaseInfoList(List<BaseInfoBean> list){
        if (list.size()>500){
            baseInfoMapper.addBaseInfoList(list.subList(0,500));
            subBaseInfoList(list.subList(500,list.size()));
        }else{
            baseInfoMapper.addBaseInfoList(list);
        }

    }
}
